<template>
  <div>
    <vab-card>
      <template #header>
        <span class="leve_title">客户价目表</span>
      </template>
      <template #default>
        <el-form
          :ref="(el: any) => (searchFormRef = el)"
          :model="searchForm"
          label-width="130px"
          class="form_search composite_form"
        >
          <el-row :gutter="24">
            <el-col
              v-for="(item, i) in CheckSearch"
              :key="i"
              :xs="24"
              :sm="12"
              :md="12"
              :lg="8"
              :xl="8"
            >
              <!-- 默认项 -->
              <el-form-item
                v-if="item.type == 'select'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabSelectForm
                  v-model.trim="searchForm[item.prop]"
                  :multiple="item.multiple"
                  :options="selectOptions(item.prop)"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
              <!-- input -->
              <el-form-item
                v-if="item.type == 'input'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabInputForm
                  v-model.trim="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
              <!-- time -->
              <el-form-item
                v-if="item.type == 'time'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabTimeForm
                  v-model="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
              <!-- 复合查询 -->
              <div class="flex" v-if="item.type == 'composite'">
                <span class="composite">
                  <el-select
                    class="composite_label"
                    v-model="composite[`compositeValue${item.prop}`]"
                    @change="(value: any) => {
                      handleComposite(value, item.prop)
                    }"
                  >
                    <el-option
                      v-for="jtem in composite[`compositeArray${item.prop}`]"
                      :key="jtem.value"
                      :label="jtem.label"
                      :value="jtem.value"
                    />
                  </el-select>
                </span>
                <VabInputForm
                  v-if="composite[`${ReturnFormType(item.prop)}`] == 'input'"
                  v-model="composite[composite[`compositeValue${item.prop}`]]"
                  @keyup.enter.native="onkeydown"
                />
                <VabTimeForm
                  v-if="composite[`${ReturnFormType(item.prop)}`] == 'time'"
                  v-model="composite[composite[`compositeValue${item.prop}`]]"
                  @keyup.enter.native="onkeydown"
                />

                <el-select
                  class="width_100"
                  v-if="composite[`${ReturnFormType(item.prop)}`] == 'select'"
                  v-model="composite[composite[`compositeValue${item.prop}`]]"
                  filterable placeholder="请选择"
                  clearable
                 >
                  <el-option
                    v-for="jtem in selectOptions(composite[`compositeValue${item.prop}`])"
                    :key="jtem.value"
                    :label="jtem.label"
                    :value="jtem.value"
                  />
                </el-select>
              </div>
            </el-col>
            <!-- 按钮 -->
            <el-col :xs="24" :sm="24" :md="12" :lg="24" :xl="24">
              <div class="flex_just_end" style="padding-top: 12px;">
                <el-button size="small" type="primary" @click="handleSearch()">
                  查询
                </el-button>
                <el-button size="small" @click="resetForm(searchFormRef)">
                  重置
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </vab-card>
    <!-- 主 -->
    <vab-card shadow="always">
      <template #header>
        <div class="flex_sb">
          <span class="leve2_title">价目表列表</span>
          <div class="flex_just_end">
            <el-button size="small" class="button_update" @click="handleClick('withdraw')">
              审核撤回
            </el-button>
            <el-button size="small" class="button_update" @click="handleClick('stop')">
              停用
            </el-button>
            <el-button size="small" class="button_update" @click="handleClick('update')">
              更新
            </el-button>
            <el-button size="small" class="button_update" @click="handleClick('copy')">
              复制
            </el-button>
            <el-button size="small" class="button_update" type="primary" @click="handleClick('create')">
              新建
            </el-button>
          </div>
        </div>
      </template>
      <el-table
        border
        height="430"
        style="width: 100%"
        :data="data.dataSource"
        v-loading="data.loading"
      >
        <el-table-column align="center" width="40" fixed="left">
          <template #default="scope">
            <label
              class="el-checkbox"
              :class="{ 'is-checked': radioKey == scope.row.id }"
              @click="handleCurrentChange(scope.row)"
            >
              <span
                class="el-checkbox__input"
                :class="{ 'is-checked': radioKey == scope.row.id }"
              >
                <span class="el-checkbox__inner"></span>
              </span>
            </label>
          </template>
        </el-table-column>
        <el-table-column label="序号" align="center" width="60">
          <template #default="scope">
            <span
              class="ellipsis"
              v-text="(data.pageNum - 1) * data.pageSize + (scope.$index + 1)"
            ></span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, i) in data.cloums"
          :key="i"
          :width="item.width"
          :prop="item.prop"
          :label="item.label"
          :align="item.type == 'money' || item.type == 'number' ? 'right' : 'center'
            "
        >
          <template #default="scope">
            <!-- 自定义 -->
            <div v-if="item.type == 'custom'">
              <span
                v-if="item.prop == 'number'"
                class="ellipsis link"
                @click="() => {
                  router.push('/customer/priceListDetail?id=' + scope.row.id)
                }
                  "
              >
                {{ scope.row[item.prop] || '--' }}
              </span>
              <span
                v-if="item.prop == 'customer'"
              >
                {{ ProductNumberName(scope.row) }}
              </span>
              <span
                v-if="item.prop == 'forbid_status_str'"
              >
                <el-tag  class="ml-2" :type="forbidStatusColor(scope.row.forbid_status_str)">{{ scope.row.forbid_status_str || '--' }}</el-tag>
              </span>

            </div>
            <!-- 正常 -->
            <div v-else class="ellipsis">
              {{ _FieldFormat(scope.row[item.prop], item.type) }}
            </div>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" align="center" width="100" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.status == 0 || row.status == 3" size="small" type="primary" @click="handleOperate('toHandle', row.id)">去处理</el-button>
            <el-button v-else size="small" type="primary" @click="handleOperate('toDetail', row.id)"
            >查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex_just_end">
        <el-pagination
          background
          small="small"
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total, prev, pager, next,sizes, jumper"
          :page-sizes="[20, 50, 100, 200]"
          :pager-count="10"
          :total="data.count"
          @current-change="handlePageNum"
          @size-change="handlePageSize"
        />
      </div>
    </vab-card>
  </div>
</template>
<!-- 库存查询 -->
<script lang="ts" setup>
defineOptions({
  name: 'PriceListCheck',
})
/**
 * @import
 */
import {
  CheckSearch,
  PriceOutsideOptions,
  CheckHostCloums,
  forbidStatusColor,
  CheckCompositeSearch1,
  CheckCompositeSearch3,
  CheckCompositeSearch2,
} from './component/PriceOutside/tools'
import { DateFormat, FieldFormat } from '~/src/utils/utils'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { customerPriceList, customerPriceSearch, customerPriceStop, customerPriceRevokeExamine } from '~/src/api/dms/customer';
import { organization_list } from '~/src/api/dms/organization';
/**
 * @var
 */
const router = useRouter()
const route = useRoute()

const proxy: any = getCurrentInstance()?.proxy


const searchFormRef = ref<any>(null)
const searchForm = reactive<any>({})
const data = reactive<any>({
  dataSource: [],
  cloums: [],
  pageNum: 1,
  pageSize: 20,
  count: 0,
  search: {},
})
data.dataSource = []
data.cloums = CheckHostCloums


let isCheck = ref(false)
// 订单占有弹窗
const currentRow = ref<any>(null) //选中块
const radioKey = ref<any>(-1) //唯一值

/**
 * @复合体 -start
 */
// 复合筛选项
const composite = reactive<any>({
  value: '',
  // form类型
  formType1: 'select',
  formType2: 'select',
  formType3: 'select',

  // 复合筛选值
  compositeValue1: 'status',
  compositeValue2: 'forbid_status',
  compositeValue3: 'customer_name',
  // 复合数组
  defaultCompositeArray2: [...CheckCompositeSearch2],
  defaultCompositeArray1: [...CheckCompositeSearch1],
  defaultCompositeArray3: [...CheckCompositeSearch3],

  compositeArray1: [],
  compositeArray2: [],
  compositeArray3: [],

  effective_date: '', // 生效时间
  expiry_date: '', // 失效时间
  create_user_id: '', // 创建人
  update_user_id: '', // 更新人
  customer_name: '', // 客户名称id
  customer_number_id: '', // 客户编码ID
  customer_type_id: '', // 客户类型id
  customer_group_id: '', // 客户分组ID

})
// 原始数据
const getComposite = () => {
  composite.compositeArray1 = CheckCompositeSearch1
  composite.compositeArray2 = CheckCompositeSearch2
  composite.compositeArray3 = CheckCompositeSearch3
}
getComposite()
// 筛选块
/**
 * @复合体 -end
 */

/**
 * @method
 */
const handleSearch = async (value = '') => {
  isCheck.value = true
  await _GetProductList()
  ElMessage({
    message: '查询成功',
    type: 'success',
  })
}
// 重置
const resetForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  isCheck.value = false
  radioKey.value = -1
  currentRow.value = null

  // 重置复合查询
  for (let index = 1; index <= 3; index++) {
    composite[`formType${index}`] = 'select'
    composite[`compositeValue${index}`] = index == 1 ? 'status' : (index == 2 ? 'forbid_status' : 'customer_name')
  }

  composite['status'] = ''
  composite['forbid_status'] = ''
  composite['effective_date'] = ''
  composite['expiry_date'] = ''
  composite['create_user_id'] = ''
  composite['update_user_id'] = ''
  composite['customer_name'] = ''
  composite['customer_number_id'] = ''
  composite['customer_type_id'] = ''
  composite['customer_group_id'] = ''

  await getComposite()
  await formEl.resetFields()
  await _GetProductList()
  ElMessage({
    message: '重置成功',
    type: 'success',
  })
}
// 回车
const onkeydown = (value: any) => {
  isCheck.value = true
  _GetProductList()
}
// 复合筛选
const handleComposite = async (eventV: any, prop: number | string) => {
  let row: any = null
  row = await composite[`compositeArray${prop}`].filter((item: any) => { return eventV == item.value })

  // 复合筛选不可重复
  if (prop == 1) {

    composite['compositeArray2'] = await composite['defaultCompositeArray2']
      .filter((item: any) => { return item.value != eventV && item.value != composite['compositeValue3'] })
    composite['compositeArray3'] = await composite['defaultCompositeArray3']
      .filter((item: any) => { return item.value != eventV && item.value != composite['compositeValue2'] })
  }

  if (prop == 2) {
    composite['compositeArray1'] = composite['defaultCompositeArray1']
      .filter((item: any) => { return item.value != eventV && item.value != composite['compositeValue3'] })
    composite['compositeArray3'] = composite['defaultCompositeArray3']
      .filter((item: any) => { return item.value != eventV && item.value != composite['compositeValue1'] })
  }

  if (prop == 3) {
    composite['compositeArray1'] = composite['defaultCompositeArray1']
      .filter((item: any) => { return item.value != eventV && item.value != composite['compositeValue2'] })
    composite['compositeArray2'] = composite['defaultCompositeArray2']
      .filter((item: any) => { return item.value != eventV && item.value != composite['compositeValue1'] })
  }

  composite[`formType${prop}`] = row[0].formType
  composite[`compositeValue${prop}`] = eventV
}
// 单选
const handleCurrentChange = (row: any) => {
  if (row.id == radioKey.value) {
    radioKey.value = -1
    currentRow.value = null
    return
  }
  radioKey.value = row.id
  currentRow.value = row
}
// 页码
const handlePageNum = (value: any) => {
  data.pageNum = value
  _GetProductList()
}
// 页数
const handlePageSize = (value: any) => {
  data.pageSize = value
  _GetProductList()
}

const ReturnFormType = (value: number | string) => {
  return `formType${value}`
}
// 点击事件
const handleClick = (value: any) => {

  if (value == 'create') {
    router.push({
      path: '/customer/priceListCreate',
      query: {
        from: 'create'
      }
    })
    return
  }
  if (!currentRow.value) {
    ElMessage({ type: 'warning', message: '请选择需要操作的价目表！' })
    return
  }

  const { id, status, forbid_status } = currentRow.value



  // 撤回
  if (value == 'withdraw') {
    if (status != 1 && status != 4) {
      ElMessage({ type: 'warning', message: '该价目表无审核中的内容!' })
      return
    }
    customerPriceRevokeExamine({ id }).then((res: any) => {
      ElMessage({ type: 'success', message: '撤回成功!' })
      currentRow.value = null
      radioKey.value = -1
      _GetProductList()
    }).catch((err: any) => {

    })
    return
  }
  if (value == 'stop') {
    if (status == 8) {
      ElMessage({ type: 'warning', message: '该价目表已停用!' })
      return
    }
    if (status == 0 || status == 1 || status == 3 || status == 4) {
      ElMessage({ type: 'warning', message: '该价目表无停用中的内容!' })
      return
    }
    customerPriceStop({ id }).then((res: any) => {
      ElMessage({ type: 'success', message: '停用成功!' })
      radioKey.value = -1
      currentRow.value = null
      _GetProductList()
    }).catch((err: any) => {

    })
    return
  }

  // 更新
  if (value == 'update') {
    if(status == 1 || status == 4) {
      proxy.$Message('该价目表状态，无法进行更新操作！', 'warning')
      return
    }

    if (forbid_status == 1) {
      proxy.$Message('该价目表已失效，无法进行更新操作！', 'warning')
      return
    }
  }

  // 草稿状态
  if (value == 'update' && status == 0) {
    ElMessageBox({
      title: '提示',
      message: h('p', null, [
        h('span', undefined, '该订单尚未提交，可直接点击'),
        h('span', {
          style: 'cursor: pointer;font-weight: 600',
          onClick: () => {
            handleOperate('toHandle', currentRow.value.id)
            //关闭弹窗
            ElMessageBox.close()
          }

        }, '【去处理】',),
        h('span', undefined, '按钮进行编辑'),
      ]),

      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    return
  }

  if (value == 'copy' || value == 'update') {
    router.push({
      path: '/customer/priceListCreate',
      query: {
        id: currentRow.value.id,
        from: value
      }
    })
  }
}
// 操作事件
const handleOperate = (value: string, id: string | number) => {
  if (value == 'toHandle') {
    router.push({ path: '/customer/priceListCreate', query: { id, from: 'toHandle' } })
  }
  if (value == 'toDetail') {
    router.push({ path: '/customer/priceListDetail', query: { id } })
  }
}
// 筛选项格式化
const selectOptions = (value: string) => {
  if (JSON.stringify(data.search) == '{}') return
  if (!value) return
  return PriceOutsideOptions(data.search, value)
}
// 字段级格式化
const _FieldFormat = (value: string, type = '') => {
  if (type == 'time') return DateFormat(value, 'YYYY-MM-DD')
  return FieldFormat(value, type)
}

//子集客户
const ProductNumberName = (row: any) => {
  if (!row.customer_name && !row.customer_number) return '--'
  return `${row.customer_number}-${row.customer_name}`
}
// 筛选项
const _GetProductSearch = async () => {
  try {
    const res = await customerPriceSearch({})
    const resUse = await organization_list({})
    data.search = await res.data
    data.search.use_org_id = resUse.data
  } catch (error) { }
}
// 获取数据
const _GetProductList = async () => {
  data.loading = true

  let _searchForm = { ...searchForm }
  let _composite = { ...composite }

  if (!isCheck.value) {
    _searchForm = {}
    _composite = {}
  }

  const {
    effective_date,
    expiry_date,
    create_user_id,
    update_user_id,
    customer_name,
    customer_number_id,
    status,
    forbid_status,
    customer_type_id,
    customer_group_id,
  } = _composite

  const query = {
    page: data.pageNum,
    limit: data.pageSize,
    filter: {
      use_org_id: _searchForm.use_org_id || '', // 使用组织
      number: _searchForm.number || '', // 价目表编码
      name: _searchForm.name || '', // 价目表名称
      status: status || '', // 价目表状态
      forbid_status: forbid_status || '',
      customer_type_id: customer_type_id || '', // 客户类型id
      customer_group_id: customer_group_id || '', // 客户分组ID
      effective_date: effective_date ? DateFormat(effective_date[0]) : '', // 生效时间
      expiry_date: effective_date ? DateFormat(effective_date[1]) : '', // 失效时间
      create_user_id: create_user_id || '', // 创建人
      update_user_id: update_user_id || '', // 更新人
      customer_name: customer_name || '', // 客户名称id
      customer_number_id: customer_number_id || '', // 客户编码ID
    },
  }

  try {
    const res = await customerPriceList({ ...query })
    data.dataSource = res.data.list
    data.count = res.data.count
    data.loading = false
  } catch (error) { }
}
onActivated(async () => {

  const { priceListName } = route.query

  await _GetProductSearch()

  currentRow.value = null
  radioKey.value = -1

  // 发生跳转
  if (priceListName) {

    searchForm.name = await Number(priceListName)
    await handleSearch()
    // 清空路由参数
    router.replace({ query: {} })
    return
  }
  _GetProductList()

})
</script>

<style lang="scss" scoped>
@import '../../components/public.scss';
</style>
./component/priceOutside/tools
